package com.moonstar;

import javax.swing.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import static com.moonstar.ProcessAClient.SENDMESSAGE_PORT;

public class SaveMessageThread implements Runnable {


    @Override
    protected void finalize() throws Throwable {
        //线程销毁前，将datagramSocket释放掉
        datagramSocket.close();
        super.finalize();
    }

    public JTextArea jTextArea;
    public static DatagramSocket datagramSocket;

    SaveMessageThread(){
    }

    public SaveMessageThread(JTextArea jTextArea) {
        this.jTextArea=jTextArea;
    }

    static {
        try {
            datagramSocket = new DatagramSocket(SENDMESSAGE_PORT);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    //调出一个线程去监听线程A的SendMessage的动作
    @Override
    public void run() {
        try {
            while (true){
                DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);
                datagramSocket.receive(dp);
                byte[] data = dp.getData();
                String dataStr = new String(data, 0,dp.getLength());
                //更新消息框
                jTextArea.setText(dataStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
